package com.shaokel;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.junit.Test;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QR {

    public static void main(String[] args) {
        //创建工具类对象
        MultiFormatWriter m = new MultiFormatWriter();
        //利用m来创建二维码
        /*
           m.encode();     encode()的五个参数
          String contents,         表白内容
          BarcodeFormat format,    画的是一维还是二维
          int width,               宽
          int height,              高
          Map<EncodeHintType,?> hints   二维码的其他信息
        * */
        String contents = "HelloWorld";
        BarcodeFormat b = BarcodeFormat.QR_CODE;//二维码     BarcodeFormat    枚举类
        int width = 500;
        int height = 500;
        Map map = new HashMap();
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);//二维码容错率   7%
        map.put(EncodeHintType.CHARACTER_SET,"UTF-8");//编码格式
        map.put(EncodeHintType.MARGIN,1);

        BitMatrix matrix = null;
        try {
            matrix = m.encode(contents, b, width, height, map);//生成一个二维码对象       存储在内存中

            //将内存中的二维码对象转换为图片
            BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
            //将二维码显示出来      目前还在内存中
            for (int i = 0; i < width; i++) {
                for (int j = 0; j < height; j++) {
                    image.setRGB(i,j,matrix.get(i,j)? Color.WHITE.getRGB():Color.BLACK.getRGB());
                }
            }

            //将内存中的二维码显示在硬盘中
            String s = System.getProperty("user.dir");//获取当前路径
//            File file = new File(s+"/二维码.png");
            File file = new File("D:/二维码.png");
            //将image对象以png存储到file中
            boolean flag = ImageIO.write(image, "png", file);
            //根据flag进行后续判断
            if(flag){
                System.out.println("二维码生成成功!");
            }else{
                System.out.println("二维码生成失败!");
            }
        } catch (WriterException | IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void c(){
        System.out.println(System.getProperty("user.dir"));
        System.out.println(this.getClass().getResource(""));
        System.out.println(this.getClass().getResource("/").getPath());
        System.out.println(new File("").getAbsoluteFile());
    }

}
